package com.pan.annotation.aspect;

import com.pan.annotation.TicketCheck;
import com.pan.annotation.enumn.IdentityEnum;
import com.pan.excep.error.MyCutException;
import com.pan.tools.ArrayTools;
import com.pan.tools.RedisTools;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import java.lang.reflect.Method;

@Aspect
@Component
public class TicketCheckAspect {

    @Resource
    public RedisTools redisTools;

    @Pointcut("@annotation(com.pan.annotation.TicketCheck)")
    public void annotationCut(){}

    @Before("annotationCut()")
    public void ticketCheck(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Object[] args = joinPoint.getArgs();
        String[] parameterNames = signature.getParameterNames();
        TicketCheck ticketCheck = method.getAnnotation(TicketCheck.class);
        String ticket = (String) args[ArrayTools.indexOf(parameterNames,ticketCheck.ticketName())];
        Long operatorId = (Long) args[ArrayTools.indexOf(parameterNames,ticketCheck.idName())];
        String role = ticketCheck.identity().name();
        String key = role+":"+ticket;
        Boolean isUser = redisTools.exists(key).getData();
        if (!isUser){
            throw new MyCutException("没有登录信息",403);
        }
        Long ticketUserId = Long.parseLong((String) redisTools.hget(role+":"+ticket,"id").getData());
        if (!ticketUserId.equals(operatorId)&&!role.equals(IdentityEnum.admin)){
            throw  new MyCutException("你没有该账户权限",403);
        }

    }

}
